package org.heart.springsecurity.JwtToken;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.List;

public class TokenProvider {

    private static final String TOKEN_SECRET = "!*@&^%$#QAZPLGFSJWURHGJG";

    public static String createAccessToken(int userId, List<Object> list) {
        try {
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.HOUR, 2);
            JWTCreator.Builder builder = JWT.create();
//            map.forEach(builder::withClaim);
            return builder.withExpiresAt(instance.getTime())
                    .withIssuer("sys")
                    .withAudience("user")
                    .withClaim("scope", list)
                    .withClaim("userId", userId)
                    .sign(Algorithm.HMAC512(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException e) {
            throw new RuntimeException("create token failure ");
        }
    }

    public static String createRefreshToken() {
        try {
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.DATE, 2);
            JWTCreator.Builder builder = JWT.create();
            return builder.withExpiresAt(instance.getTime())
                    .withIssuer("sys")
                    .withAudience("user")
                    .sign(Algorithm.HMAC512("refreshToken1988"));
        } catch (IllegalArgumentException | JWTCreationException e) {
            throw new RuntimeException("create token failure ");
        }
    }

    public static String getUserId(String tokenVal) {
        if (tokenVal == null) {
            throw new RuntimeException("token is null!");
        }
        try {
            DecodedJWT decode = JWT.decode(tokenVal);
            return decode.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            throw new RuntimeException();
        }
    }



    /**
     * @param tokenKey token创建时设置参数
     * @param token    token 字符串
     * @return
     */
    public static String getToken(String tokenKey, String token) {
        if (token == null) {
            throw new RuntimeException("token is null!");
        }
        if (tokenKey == null) {
            throw new RuntimeException("tokenKey is null!");
        }
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim(tokenKey).asString();
        } catch (JWTDecodeException e) {
            throw new RuntimeException();
        }
    }
}
